﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SetFocusDemo.Reflection.Contract;
using System.IO;
using System.Reflection;



namespace SetFocusDemo.Reflection.Loader
{
    public class PluginLoader
    {
        public static IPluginInterface[] GetPlugins(string directory)
        {
            if (String.IsNullOrEmpty(directory)) { return null; } //sanity check

            DirectoryInfo info = new DirectoryInfo(directory);

            if (!info.Exists) { return null; } //make sure directory exists

            List<IPluginInterface> plugins = new List<IPluginInterface>();

            foreach (FileInfo file in info.GetFiles("*.dll")) //loop through all dll files in directory
            {
                //using Reflection, load Assembly into memory from disk
                Assembly currentAssembly = Assembly.LoadFile(file.FullName);

                //Type discovery to find the type we're looking for which is IPluginInterface
                foreach (Type type in currentAssembly.GetTypes())
                {
                    if (!type.ImplementsInterface(typeof(IPluginInterface)))
                    {
                        continue;
                    }

                    //Create instance of class that implements IPluginInterface and cast it to type
                    IPluginInterface plugin = (IPluginInterface)Activator.CreateInstance(type);
                    //IPluginInterface and add it to our list
                    plugins.Add(plugin);

                }
            }
            return plugins.ToArray();
        }
    }
}
